package com.opencee.cloud.core.feign;

import com.opencee.common.exception.BaseFeignRpcErrorException;
import com.opencee.common.model.ApiErrorResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * /**
 * 当调用服务时，如果服务返回的状态码不是200，就会进入到Feign的ErrorDecoder中，因此如果我们要解析异常信息，就要重写ErrorDecoder：
 *
 * @author yadu
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    private ObjectMapper objectMapper;


    public FeignErrorDecoder(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public Exception decode(String methodKey, Response response) {
        Exception exception = null;
        try {
            String json = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
            exception = new RuntimeException(json);
            if (StringUtils.isBlank(json)) {
                return null;
            }
            ApiErrorResult body = objectMapper.readValue(json, ApiErrorResult.class);
            // 业务异常包装成自定义异常类
            if (response.status() != HttpStatus.OK.value()) {
                exception = new BaseFeignRpcErrorException(body.getCode(), body.getError());
            }
        } catch (IOException ex) {
        }
        return exception;
    }
}
